﻿///***************************************************************
/// 시  스  템 : Updms.Car
/// 단위시스템 : CAR
/// 계      층 : Presentation Layer
/// 프로그램명 : Car2010r
/// 파  일  명 : Car2010r.aspx.cs
/// 설      명 : 주유정보챠트
///***************************************************************
/// 수정ID 일자       이름     내용
///---------------------------------------------------------------
/// CH001  2008-08-22 송시명   최초 작성
///***************************************************************
using System;
using System.Data;
using System.Drawing;
using System.Web.UI;

using SMFramework.Data;
using SMFramework.Utility;

using Base.Dac;
using Updms.Car.Exe;


namespace Updms.Car
{
	public partial class Car2010r : Updms.Common.BaseClass.PageBase
	{
		#region 전역영역

		//프로그램상수
		public static readonly string PID = "Car2010r";
		public static readonly string gs_path_info = "/updms/Car/" + PID + ".aspx";

		Global global = new Global();
		CommCode.Com com = new CommCode.Com(LANG_SET);
		CommCode.Car car = new CommCode.Car(LANG_SET);

		//검색
		protected string kw1 = "";	//차량ID
		protected string kw2 = "";	//주유일(부터)
		protected string kw3 = "";	//주유일(까지)
		protected string kw4 = "";	//조회구분
		protected string kw5 = "";	//챠트넓이

		//메뉴 선택값
		protected string gs_sm = "";

		// 페이지모드
		private string gs_page_mode = "";

		#endregion

		#region Page_Load, OnPageLoad

		protected void Page_Load(object sender, EventArgs e)
		{
			SetInit();
			if (!Page.IsPostBack)
			{
				// 최초 화면 로딩시 처리해야 할 부분
				OnPageLoad();
			}
		}

		// OnPageLoad
		private void OnPageLoad()
		{
			SetLiterals(global.GetLabelInfoByPgmId(PID, LANG_SET));
			SetClientScript();
			SetCarInfo();
			SetSearchDiv();
			SetSearchItem();
			SetChartWidth();
			SetSearchParameter();
		}

		#endregion

		#region InitializeComponent

		private void InitializeComponent()
		{
			this.Load += new System.EventHandler(this.Page_Load);
			this.PreRender += new System.EventHandler(this.Page_PreRender);
		}

		#endregion

		#region SetClientScript

		private void SetClientScript()
		{
			//엔터검색
			txt_search_refuelling_dt_from.Attributes.Add("onkeypress", "enterSearchOnPage(event)");
			txt_search_refuelling_dt_to.Attributes.Add("onkeypress", "enterSearchOnPage(event)");
		}

		#endregion

		#region SetInit, SetSearchParameter, ShowKeywordLabel

		//초기값설정
		private void SetInit()
		{
			lbl_search_flag.Text = "INIT";			

			gs_sm = (Request.QueryString["sm"] == null || Request.QueryString["sm"].Trim().Length != 7)
					? global.GetDirDepth(PID) : Request.QueryString["sm"].ToString();
		}

		//검색파라미터
		private void SetSearchParameter()
		{
			switch (lbl_search_flag.Text.Trim().ToUpper())
			{
				case "INIT":
					if (String.IsNullOrEmpty(Request.QueryString["kw1"]))	// url에 값이 없으면
					{
						kw1 = ddl_search_car_id.SelectedValue;
					}
					else
					{
						kw1 = Server.UrlDecode(Request.QueryString["kw1"]);
						ddl_search_car_id.SelectedValue = kw1;
					}

					if (String.IsNullOrEmpty(Request.QueryString["kw2"]))	// url에 값이 없으면
					{
						if (String.IsNullOrEmpty(txt_search_refuelling_dt_from.Text))
						{
							kw2 = DateUtil.GetMonthEx(-12);	// 오늘부터 12개월전
							txt_search_refuelling_dt_from.Text = kw2;
						}
						else
						{
							kw2 = txt_search_refuelling_dt_from.Text.Trim();
						}
					}
					else
					{
						kw2 = Server.UrlDecode(Request.QueryString["kw2"]);
						txt_search_refuelling_dt_from.Text = kw2;
					}

					if (String.IsNullOrEmpty(Request.QueryString["kw3"]))	// url에 값이 없으면
					{
						if (String.IsNullOrEmpty(txt_search_refuelling_dt_to.Text))
						{
							kw3 = DateUtil.GetMonthEx(0);	// 오늘
							txt_search_refuelling_dt_to.Text = kw3;
						}
						else
						{
							kw3 = txt_search_refuelling_dt_to.Text.Trim();
						}
					}
					else
					{
						kw3 = Server.UrlDecode(Request.QueryString["kw3"]);
						txt_search_refuelling_dt_to.Text = kw3;
					}
					
					if (String.IsNullOrEmpty(Request.QueryString["kw4"]))	// url에 값이 없으면
					{
						kw4 = ddl_search_div.SelectedValue;
					}
					else
					{
						kw4 = Server.UrlDecode(Request.QueryString["kw4"]);
						ddl_search_div.SelectedValue = kw4;
					}

					if (String.IsNullOrEmpty(Request.QueryString["kw5"]))	// url에 값이 없으면
					{
						kw5 = ddl_search_chart_width.SelectedValue;
					}
					else
					{
						kw5 = Server.UrlDecode(Request.QueryString["kw5"]);
						ddl_search_chart_width.SelectedValue = kw5;
					}

					break;
				case "SEARCH":
					kw1 = ddl_search_car_id.SelectedValue;
					kw2 = String.IsNullOrEmpty(txt_search_refuelling_dt_from.Text) ? DateUtil.GetMonthEx(-12) : txt_search_refuelling_dt_from.Text.Trim();
					kw3 = String.IsNullOrEmpty(txt_search_refuelling_dt_to.Text) ? DateUtil.GetMonthEx(0) : txt_search_refuelling_dt_to.Text.Trim();
					kw4 = ddl_search_div.SelectedValue;
					kw5 = ddl_search_chart_width.SelectedValue;		
					break;
			}
		}	

		#endregion

		#region 마스터 Method (SetCarInfo, SetSearchDiv, SetSearchItem, SetYearMonth, SetChartWidth)

		//차량ID
		private void SetCarInfo()
		{
			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();
			Car1010m_NT _Car1010m_NT = new Car1010m_NT();

			lo_dp.AddProperty("ls_use_yn", typeof(string), "Y");	//사용여부가 Y인것만

			lo_ds.Merge(_Car1010m_NT.GetCarInfoList(lo_dp));

			ddl_search_car_id.Items.Clear();
			ddl_search_car_id.DataSource = lo_ds;
			ddl_search_car_id.DataMember = "UPDMS_CAR_INFO";
			ddl_search_car_id.DataTextField = "Text";
			ddl_search_car_id.DataValueField = "Value";
			ddl_search_car_id.DataBind();
		}

		//조회구분
		private void SetSearchDiv()
		{
			car.SetSearchDiv(ddl_search_div);
		}

		//조회항목
		private void SetSearchItem()
		{
			car.SetSearchItem(cbl_search_item);

			//모든 조회항목을 선택
			if (cbl_search_item.Items.Count > 0)
			{
				for (int i=0; i<cbl_search_item.Items.Count; i++ )
				{
					cbl_search_item.Items[i].Selected = true;
				}
			}
		}

		// 검색조건의 년월일설정 - 기간지정
		private void SetYearMonth(int li_term)
		{
			txt_search_refuelling_dt_from.Text = DateUtil.GetMonthEx(li_term);
			txt_search_refuelling_dt_to.Text = DateUtil.GetMonthEx(0);
		}

		// 검색조건의 년월일설정 - 전체
		private void SetYearMonth()
		{
			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();
			Car1010m_NT _Car1010m_NT = new Car1010m_NT();

			lo_dp.AddProperty("ls_car_id", typeof(string), kw1);

			lo_ds.Merge(_Car1010m_NT.GetMinNMaxExpenseDt(lo_dp));

			txt_search_refuelling_dt_from.Text = DataSetUtil.GetFldStr(lo_ds, "UPDMS_CAR_INFO","Min_Dt");
			txt_search_refuelling_dt_to.Text = DataSetUtil.GetFldStr(lo_ds, "UPDMS_CAR_INFO", "Max_Dt");
		}

		//챠트넓이
		private void SetChartWidth()
		{
			com.SetChartWidth(ddl_search_chart_width);
			ddl_search_chart_width.SelectedValue = CHART_RESOLUTION;
		}

		#endregion

		#region 챠트 (DrawFuelInfo, SearchProcess)

		private void DrawFuelInfo()
		{
			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();
			
			//일단 모두 숨긴다.
			table_chart_distance.Visible
				= table_chart_quantity.Visible = table_chart_amount_per_liter.Visible = table_chart_fuel_efficiency.Visible = false;
			
			//검색
			lo_dp.AddProperty("ls_car_id", typeof(string), kw1);
			lo_dp.AddProperty("ls_refuelling_dt_from", typeof(string), kw2);
			lo_dp.AddProperty("ls_refuelling_dt_to", typeof(string), kw3);
			lo_dp.AddProperty("ls_search_div", typeof(string), kw4);

			using (Car2010r_NT _Car2010r_NT = new Car2010r_NT())
			{
				lo_ds.Merge(_Car2010r_NT.GetFuelInfo(lo_dp));
			}
			int li_count = DataSetUtil.GetRowCount(lo_ds, "UPDMS_CAR_REPORT");

			if (li_count > 0)
			{
				for (int i = 0; i < cbl_search_item.Items.Count; i++)
				{
					if (cbl_search_item.Items[i].Selected == true)
					{
						switch (cbl_search_item.Items[i].Value)
						{
							case "AC001":
								table_chart_distance.Visible = true;
								DrawDistance(lo_ds, li_count);
								break;
							case "AC002":
								table_chart_quantity.Visible = true;
								DrawQuantity(lo_ds, li_count);
								break;
							case "AC003":
								table_chart_amount_per_liter.Visible = true;
								DrawAmountPerLiter(lo_ds, li_count);
								break;
							case "AC004":
								table_chart_fuel_efficiency.Visible = true;
								DrawFuelEfficiency();
								break;
						}
					}
				}
			}
			else
			{
				//CallMsgBoxInAjax("MSG_ERR_111");	// 등록된 내용이 없습니다
			}
		}

		#region 누적주행거리
		
		//누적주행거리
		private void DrawDistance(DataSet lo_ds, int li_count)
		{
			chart_distance.Data.Series = 1;

			//넓이
			chart_distance.Width = Convert.ToInt32(kw5);
		
			if (DataSetUtil.CheckRowCount(lo_ds, "UPDMS_CAR_REPORT"))
			{
				chart_distance.Data.Clear();

				for (int i = 0; i < li_count; i++)
				{
					chart_distance.Data[0, i] = DataSetUtil.GetFldInt(lo_ds, "UPDMS_CAR_REPORT", i, "Distance");

					//X축 라벨링
					chart_distance.AxisX.Labels[i] = DataSetUtil.GetFldStr(lo_ds, "UPDMS_CAR_REPORT", i, "Refuelling_Dt");
				}
			}
		}
		
		#endregion

		#region 주유량

		//주유량
		private void DrawQuantity(DataSet lo_ds, int li_count)
		{
			chart_quantity.Data.Series = 1;

			//넓이
			chart_quantity.Width = Convert.ToInt32(kw5);

			if (DataSetUtil.CheckRowCount(lo_ds, "UPDMS_CAR_REPORT"))
			{
				chart_quantity.Data.Clear();

				for (int i = 0; i < li_count; i++)
				{
					chart_quantity.Data[0, i] = DataSetUtil.GetFldDbl(lo_ds, "UPDMS_CAR_REPORT", i, "Quantity");

					//X축 라벨링
					chart_quantity.AxisX.Labels[i] = DataSetUtil.GetFldStr(lo_ds, "UPDMS_CAR_REPORT", i, "Refuelling_Dt");
				}
			}
		}

		#endregion

		#region 리터당가격

		//리터당가격
		private void DrawAmountPerLiter(DataSet lo_ds, int li_count)
		{
			chart_amount_per_liter.Data.Series = 1;

			//넓이
			chart_amount_per_liter.Width = Convert.ToInt32(kw5);
		
			if (DataSetUtil.CheckRowCount(lo_ds, "UPDMS_CAR_REPORT"))
			{
				chart_amount_per_liter.Data.Clear();
				
				for (int i = 0; i < li_count; i++)
				{
					chart_amount_per_liter.Data[0, i] = DataSetUtil.GetFldInt(lo_ds, "UPDMS_CAR_REPORT", i, "Amount_Per_Liter");

					//X축 라벨링
					chart_amount_per_liter.AxisX.Labels[i] = DataSetUtil.GetFldStr(lo_ds, "UPDMS_CAR_REPORT", i, "Refuelling_Dt");
				}
			}
		}
		
		#endregion

		#region 월평균연비

		//연비
		private void DrawFuelEfficiency()
		{
			chart_fuel_efficiency.Data.Series = 1;

			//넓이
			chart_fuel_efficiency.Width = Convert.ToInt32(kw5);

			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();

			//검색
			lo_dp.AddProperty("ls_car_id", typeof(string), kw1);
			lo_dp.AddProperty("ls_refuelling_dt_from", typeof(string), kw2);
			lo_dp.AddProperty("ls_refuelling_dt_to", typeof(string), kw3);

			using (Car2010r_NT _Car2010r_NT = new Car2010r_NT())
			{
				lo_ds.Merge(_Car2010r_NT.GetMonthlyAvgFuelEfficiency(lo_dp));
			}
			int li_count = DataSetUtil.GetRowCount(lo_ds, "UPDMS_CAR_REPORT");

			if (li_count > 1)
			{
				chart_fuel_efficiency.Data.Clear();
				
				for (int i = 0; i < li_count - 1; i++)	//마지막 열 (Total Average)은 제외
				{
					double ld_data = DataSetUtil.GetFldDbl(lo_ds, "UPDMS_CAR_REPORT", i, "Monthly_Fuel_Efficiency");
					chart_fuel_efficiency.Data[0, i] = ld_data;

					//X축 라벨링
					chart_fuel_efficiency.AxisX.Labels[i] = DataSetUtil.GetFldStr(lo_ds, "UPDMS_CAR_REPORT", i, "Refuelling_Dt");
				}

				//Total Average
				double ld_total_avg = DataSetUtil.GetFldDbl(lo_ds, "UPDMS_CAR_REPORT", (li_count - 1), "Monthly_Fuel_Efficiency");

				//초기화
				chart_fuel_efficiency.AxisY.CustomGridLines.Clear();

				//CustomGridLine
				ChartFX.WebForms.CustomGridLine cgl1 = new ChartFX.WebForms.CustomGridLine();
				cgl1.Value = ld_total_avg;
				cgl1.Text = "Total Avg. : " + ld_total_avg.ToString("#,###.##");
				cgl1.ShowText = true;
				cgl1.Color = Color.Red;
				cgl1.TextColor = Color.Black;
				cgl1.Alignment = StringAlignment.Far;
				cgl1.LineAlignment = StringAlignment.Near;
				cgl1.Width = 2;				
				chart_fuel_efficiency.AxisY.CustomGridLines.Add(cgl1);
			}
			else
			{
				//CallMsgBoxInAjax("MSG_ERR_111");	// 등록된 내용이 없습니다
			}
		}

		#endregion

		//검색
		private void SearchProcess()
		{
			gs_page_mode = "R";
			lbl_search_flag.Text = "SEARCH";
			SetSearchParameter();

			DrawFuelInfo();
		}

		#endregion

		#region Page_PreRender, ChangePageMode

		// Page_PreRender
		private void Page_PreRender(object sender, System.EventArgs e)
		{
			if (!Page.IsPostBack)
			{
				using (AccessCheck access = new AccessCheck())
				{
					//접근권한 체크
					if (!access.CheckPgmAccessGrant(PID, USER_ID, ACCESS_LOG_INFO))
					{
						Response.Redirect(URL_NO_AUTHORITY_REDIRECT_BASE);	//사용자의 권한은 요청하신 페이지를 볼 수 없습니다
					}
				}
			}
			ChangePageMode();
		}

		// ChangePageMode
		private void ChangePageMode()
		{
			switch (gs_page_mode)
			{
				case "":		// 처음 페이지로드시
					table_chart.Visible = false;	// line챠트
					break;
				case "R":	// 검색버튼 클릭시
					table_chart.Visible = true;	// line챠트
					break;
			}
		}

		#endregion

		#region 버튼이벤트

		//3개월
		protected void sbtn_3_m_Click(object sender, EventArgs e)
		{
			SetYearMonth(-3);
		}

		//6개월
		protected void sbtn_6_m_Click(object sender, EventArgs e)
		{
			SetYearMonth(-6);
		}

		//12개월
		protected void sbtn_12_m_Click(object sender, EventArgs e)
		{
			SetYearMonth(-12);
		}

		//전체
		protected void sbtn_all_m_Click(object sender, EventArgs e)
		{
			lbl_search_flag.Text = "SEARCH";
			SetSearchParameter();
			SetYearMonth();
		}

		//검색
		protected void ibtn_chart_Click(object sender, EventArgs e)
		{
			SearchProcess();
		}

		#endregion


	}
}
